import React from 'react';
import { Card, Form, Input, Button } from 'antd';
import UserProfileCard from '../../components/UserProfileCard';
import { useUserContext } from '../../contexts/UserContext';

const ProfilePage = () => {
  const { user, updateUser } = useUserContext();
  const [form] = Form.useForm();

  const onFinish = async (values) => {
    try {
      await updateUser(values);
      form.resetFields();
    } catch (error) {
      console.error('更新个人信息失败:', error);
    }
  };

  return (
    <>
      <Card title="编辑个人信息">
        <Form form={form} initialValues={user} onFinish={onFinish} layout="vertical">
          <Form.Item name="username" label="用户名" rules={[{ required: true }]}>
            <Input disabled />
          </Form.Item>
          <Form.Item name="email" label="邮箱" rules={[{ required: true, type: 'email' }]}>
            <Input />
          </Form.Item>
          <Form.Item name="name" label="姓名" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="phone" label="电话" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="oldPassword" label="旧密码" rules={[{ required: true, min: 6, message: '旧密码必须至少6位' }]}>
            <Input.Password />
          </Form.Item>
          <Form.Item name="newPassword" label="新密码" rules={[
            { required: true, min: 6, message: '新密码必须至少6位' },
            { pattern: /^(?=.*[A-Za-z])(?=.*\d).*$/, message: '新密码需包含字母和数字' }
          ]}>
            <Input.Password />
          </Form.Item>
          <Form.Item name="confirmPassword" label="确认新密码" dependencies={['newPassword']} rules={[
            { required: true, message: '请确认新密码' },
            ({ getFieldValue }) => ({ validator(_, value) {
              if (!value || getFieldValue('newPassword') === value) return Promise.resolve();
              return Promise.reject(new Error('两次输入的密码不一致'));
            }})
          ]}>
            <Input.Password />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">保存修改</Button>
          </Form.Item>
        </Form>
      </Card>
    </>
  );
};

export default ProfilePage;